package com.training.bt.security.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;
import com.training.bt.entity.User;


@Component
public class JwtUtil {
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private long expiration;

    private Key key;

    @PostConstruct
    public void init(){
        this.key=Keys.hmacShaKeyFor(secret.getBytes());
    }

    public String generateToken(User user){
        Date now=new Date();
        Date expiraDate=new Date(now.getTime()+expiration);

        return Jwts.builder()
                .setSubject(user.getId().toString())
                .claim("email", user.getEmail())
                .claim("role",user.getRole())
                .setIssuedAt(now)
                .setExpiration(expiraDate)
                .signWith(key,SignatureAlgorithm.HS256)
                .compact();
    }   

    public Claims parseToken(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (JwtException e) {
            throw new RuntimeException("无效的 JWT token");
        }
    }

    // 提取 userId
    public Long getUserId(String token) {
        return Long.valueOf(parseToken(token).getSubject());
    }

    public String getRole(String token) {
        return (String) parseToken(token).get("role");
    }    
}
